package com.wulab.backend.controller;

import com.wulab.backend.dto.ApiResponse;
import com.wulab.backend.dto.GeneSearchRequest;
import com.wulab.backend.utils.Option;
import com.wulab.backend.entity.GeneInfo;
import com.wulab.backend.service.GeneInfoService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("api/gene_info")
public class GeneInfoController {

    private final GeneInfoService geneInfoService;

    public GeneInfoController(GeneInfoService geneInfoService) {
        this.geneInfoService = geneInfoService;
    }

    @PostMapping("/import")
    public ApiResponse<String> importData(@RequestParam("file") MultipartFile file) {
        try {
            // 处理文件并导入数据
            geneInfoService.importGeneInfo(file);
            // 返回成功的 JSON 响应
            return new ApiResponse<>(true, "File uploaded and data imported successfully!", null);
        } catch (Exception e) {
            e.printStackTrace();
            // 返回失败的 JSON 响应
            return new ApiResponse<>(false, "Failed to import data from file: " + e.getMessage(), null);
        }
    }

    @PostMapping("/get_all_gene")
    public ApiResponse<List<GeneInfo>> getAllGene(
            @RequestBody GeneSearchRequest request
    ) {
        int page = request.getPage();
        int pageSize = request.getPageSize();
        Map<String, String> searchParams = request.getSearchParams();
        Map<String, Object> result = geneInfoService.getGeneInfo(page, pageSize, searchParams);
        List<GeneInfo> data = (List<GeneInfo>) result.get("data");
        long total = (long) result.get("total");

        // 返回 ApiResponse，直接返回 data 和 total
        return new ApiResponse<>(true, "Data fetched successfully", data, total);
    }

    @GetMapping("/get-options")
    public ApiResponse<List<Option>> getOptions(@RequestParam String column) {
        List<Option> options;
        options = geneInfoService.getOptions(column);
        // 返回 ApiResponse，直接返回 data 和 total
        return new ApiResponse<>(true, "Data fetched successfully", options, options.size());
    }
}
